package com.linkage.seapeak.activity.message;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.adapter.ItemHistoryAdapter;
import com.linkage.seapeak.adapter.ItemNewHistoryAdapter;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.pojo.MultiMessage;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MultiMessageHistoryActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    private AYSwipeRecyclerView memberList;
    private ItemNewHistoryAdapter adapter;
    List<MultiMessage> multiMessageList;
    String projectId;
    int pageNo = 1;
    int pageSize = 20;

    public static void start(Context context, String projectId){
        Intent intent = new Intent(context, MultiMessageHistoryActivity.class);
        intent.putExtra("projectId", projectId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_history, "群发消息记录");
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        memberList.startLoadFirst();
    }

    private void initView() {
        projectId = getIntent().getStringExtra("projectId");
        multiMessageList = new ArrayList<>();
        memberList = (AYSwipeRecyclerView) findViewById(R.id.member_list);
        memberList.setOnRefreshLoadLister(this);
        memberList.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        adapter = new ItemNewHistoryAdapter(MultiMessageHistoryActivity.this, multiMessageList);
        memberList.setAdapter(adapter);

        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MultiSelectActivity.start(MultiMessageHistoryActivity.this, projectId);
            }
        }, "群发消息", 0));

        memberList.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                List<CrediterUser> userList = multiMessageList.get(position).getUsers();
                if (userList == null || userList.size() == 0) {
                    showToast("消息没有成员");
                    return;
                }

                Intent intent = new Intent(MultiMessageHistoryActivity.this, MessageMemberActivity.class);
                intent.putExtra("userList", (Serializable) userList);
                startActivity(intent);
            }
        });
    }

    @Override
    public void loadFirst() {
        pageNo = 1;
        findGroupMsg(true);
    }

    @Override
    public void loadNext() {
        findGroupMsg(false);
    }

    /**
     * 获取历史消息
     */
    public void findGroupMsg(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        Network.getAPIService()
                .findGroupMsg(getUserToken(), projectId, pageNo, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            JsonObject data = json.getAsJsonObject("data");
                            JsonObject jsonpagination = data.getAsJsonObject("pagination");
                            JsonArray array = jsonpagination.getAsJsonArray("list");
                            List<MultiMessage> temp = new ArrayList<>();
                            for (int i = 0;i < array.size();i++) {
                                MultiMessage item = new Gson().fromJson(array.get(i), MultiMessage.class);
                                temp.add(item);
                            }

                            if (isFirst)
                                multiMessageList.clear();

                            multiMessageList.addAll(temp);
                            int count = jsonpagination.get("totalCount").getAsInt();
                            memberList.onFinishRequest(false, pageNo * pageSize < count);
                            pageNo++;

                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }
}
